package com.magist.manage.web.converter;

import com.magist.manage.util.GsonBuilderUtils;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.lang.Nullable;
import springfox.documentation.spring.web.json.Json;

import java.io.Writer;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class JSONHttpMessageConverter extends GsonHttpMessageConverter {

    public JSONHttpMessageConverter() {
        super.setGson(GsonBuilderUtils.create());
    }

    @Override
    protected void writeInternal(Object o, @Nullable Type type, Writer writer) throws Exception {
        // In Gson, toJson with a type argument will exclusively use that given type,
        // ignoring the actual type of the object... which might be more specific,
        // e.g. a subclass of the specified type which includes additional fields.
        // As a consequence, we're only passing in parameterized type declarations
        // which might contain extra generics that the object instance doesn't retain.
        if (type instanceof ParameterizedType) {
            getGson().toJson(o, type, writer);
        } else if(o instanceof Json) {
            writer.write(((Json) o).value());
        }
        else {
            getGson().toJson(o, writer);
        }
    }


//    @Override
//    protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage)
//            throws IOException, HttpMessageNotWritableException {
//
//        super.writeInternal(o, type, outputMessage);
//    }
}
